<template>
	<div class="v-upload">
		<div v-if="type == 'image'" style="display: flex; align-items: center; flex-wrap: wrap">
			<div class="item" v-for="(item, index) in fileList" :key="index">
				<div class="delete" v-if="!(disabled & readOnly)" @click="onDelete(index, '确定删除该图片吗？')"></div>
				<image class="image" mode="aspectFill" :src="item" @click="onPreview(index)"></image>
			</div>
			<image :class="['item upload', { disabled }]" src="/static/forms/image.png" mode="aspectFill" v-if="!readOnly & couldUpload" @click="onUpload"></image>
			<v-modal ref="vModalRef"></v-modal>
		</div>
		<div v-else-if="type == 'video'" style="display: flex; align-items: center; flex-wrap: wrap">
			<div class="item" v-for="(item, index) in fileList" :key="index">
				<div class="delete" v-if="!(disabled & readOnly)" @click="onDelete(index, '确定删除该视频吗？')"></div>
				<video class="video" mode="aspectFill" :src="item"></video>
			</div>
			<div class="box">
				<image :class="['item upload', { disabled }]" src="/static/forms/video.png" v-if="!readOnly & couldUpload" @click="onUpload"></image>
				<div class="progress">
					<progress :percent="videoProgress" v-if="visible" stroke-width="3" />
				</div>
			</div>
			<v-modal ref="vModalRef"></v-modal>
		</div>
		<div v-else class="file">
			<div class="file-image" @click="onUpload">
				<div class="box">
					<div class="file-img" v-if="!readOnly & couldUpload">
						文件
						<image :class="['image upload', { disabled }]" src="/static/forms/arrow.png"></image>
					</div>
					<div class="progress">
						<progress :percent="videoProgress" v-if="visible" stroke-width="3" />
					</div>
				</div>
			</div>
			<div class="file-item" v-for="(item, index) in fileList" :key="index">
				<image class="image" mode="aspectFill" src="/static/forms/file.png"></image>
				<div class="file-info">
					<div class="name">{{ item.name }}</div>
					<!-- <div class="size">9.3KB</div> -->
				</div>
				<div v-if="delbtn" class="file-delete" @click="onDelete(index, '确定删除该文件吗？')">删除</div>
				<div class="file-download" v-if="isDownload" @click="onDownload(item)">下载</div>
			</div>
			<v-modal ref="vModalRef"></v-modal>
		</div>
	</div>
</template>

<script>
import vModal from "./modal.vue"
import { backend } from "@/uni"

export default {
	name: "v-upload",
	model: {
		prop: "value",
		event: "update:value",
	},
	props: {
		value: {
			type: [String, Array],
			default: () => [],
		},
		max: {
			type: [String, Number],
			default: -1,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		readOnly: {
			type: Boolean,
			default: false,
		},
		type: {
			type: String,
			default: "image",
		},
		fileSize: {
			type: Number,
			default: 10,
		},
		multiple: {
			type: Boolean,
			default: false,
		},
		delbtn: {
			type: Boolean,
			default: true,
		},
		isDownload: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			videoProgress: 0,
			visible: false,
		}
	},
	computed: {
		fileList() {
			if (this.value) {
				if (typeof this.value === "string") {
					return [this.value]
				} else {
					return this.value
				}
			} else {
				return []
			}
		},
		couldUpload() {
			return this.max === -1 || this.fileList.length < this.max
		},
	},
	created() {
		// console.log(this.fileSize)
	},
	methods: {
		onUpload() {
			if (this.disabled || this.readOnly || !this.couldUpload) return
			if (this.type == "image") {
				uni.chooseImage({
					count: this.max === -1 ? 9 : this.max - this.fileList.length,
					sourceType: ["album", "camera"],
					success: async ({ tempFilePaths, tempFiles }) => {
						let resSize = tempFiles[0].size / 1024 / 1024
						if (resSize > this.fileSize) {
							uni.showToast({
								title: "图片大小不能超过" + this.fileSize + "MB",
								icon: "none",
							})
							return
						}
						const promiseList = []
						tempFilePaths.map(filePath => {
							promiseList.push(this.uploadFilePromise(filePath, function (res) {}))
						})
						const res = await Promise.all(promiseList)
						if (this.multiple) {
							this.$emit("update:value", this.fileList.concat(res.map(item => item.url)))
							this.$emit("change", this.fileList.concat(res.map(item => item.url)))
						} else {
							this.$emit("update:value", this.fileList.concat(res.map(item => item.url)))
							this.$emit("change", this.fileList.concat(res.map(item => item.url)))
						}
					},
				})
			} else if (this.type == "video") {
				uni.chooseVideo({
					sourceType: ["album", "camera"],
					success: async result => {
						let resSize = result.tempFile.size / 1024 / 1024
						if (resSize > this.fileSize) {
							uni.showToast({
								title: "视频大小不能超过" + this.fileSize + "MB",
								icon: "none",
							})
							return
						}
						const promiseList = []

						promiseList.push(this.uploadFilePromise(result.tempFilePath, function (res) {}))

						const res = await Promise.all(promiseList)
						this.$emit("update:value", res[0].url)
						this.$emit("change", res[0].url)
					},
				})
			} else {
				// todo
				uni.chooseFile({
					count: this.max === -1 ? 9 : this.max - this.fileList.length,
					sourceType: ["album", "camera"],
					success: async ({ tempFilePaths, tempFiles }) => {
						let resSize = tempFiles[0].size / 1024 / 1024
						if (resSize > this.fileSize) {
							uni.showToast({
								title: "文件大小不能超过" + this.fileSize + "MB",
								icon: "none",
							})
							return
						}
						const promiseList = []
						tempFilePaths.map(filePath => {
							promiseList.push(this.uploadFilePromise(filePath, function (res) {}))
						})
						const res = await Promise.all(promiseList)
						// this.$emit("update:value", res)
						this.$emit("update:value", this.fileList.concat(res))
						this.$emit("change", this.fileList.concat(res))
					},
				})
			}
		},
		uploadFilePromise(filePath, progressCallBack) {
			return new Promise((resolve, reject) => {
				const uploadTask = uni.uploadFile({
					url: backend + "/system/oss/upload",
					filePath,
					name: "upfile",
					header: {
						Authorization: "Bearer " + uni.getStorageSync("token") || "",
					},
					success: res => {
						const result = JSON.parse(res.data)
						if (result.code == 0) {
							resolve(result.data)
						} else {
							reject(result.msg)
						}
					},
					fail: error => {
						reject("上传失败")
					},
				})
				// 通过uploadTask 监听上传进度
				uploadTask.onProgressUpdate(res => {
					progressCallBack(res)
					console.log(res.progress)
					if (res.progress && res.progress < 100) {
						this.visible = true
						this.videoProgress = res.progress
					} else {
						setTimeout(() => {
							this.visible = false
						}, 2000)
					}
				})
			})
		},
		async onDelete(index, content) {
			try {
				const { next } = await this.$refs.vModalRef.show({
					title: "提示",
					content: content,
					center: true,
				})
				const list = this.fileList
				list.splice(index, 1)
				this.$emit("update:value", list)
				next()
			} catch (error) {}
		},
		onDownload(file) {
			window.open(file.url)
			// uni.downloadFile({
			// 	url: file.url,
			// 	header: {
			// 		Authorization: "Bearer " + uni.getStorageSync("token") || "",
			// 	},
			// 	success: res => {
			// 		uni.saveFile({
			// 			tempFilePath: res.tempFilePath,
			// 			success: function (res) {
			// 				console.log(res, "res")
			// 				uni.showToat({
			// 					title: "下载成功",
			// 					icon: "none",
			// 				})
			// 			},
			// 		})
			// 	},
			// })
		},
		onPreview(current) {
			uni.previewImage({
				current,
				urls: this.fileList,
			})
		},
	},
	components: {
		vModal,
	},
}
</script>

<style lang="scss" scoped>
.v-upload {
	width: 100%;
	display: flex;
	justify-content: flex-start;
	align-items: flex-start;
	flex-wrap: wrap;
	padding-top: 10rpx;
	.file {
		width: 100%;
		text-align: right;
		.file-item {
			margin-top: 10rpx;
			background-color: #f5f6f7;
			padding: 20rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			border-radius: 10rpx;
			.image {
				width: 55rpx;
				height: 55rpx;
			}
			.file-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				text-align: left;
				padding: 0 14rpx;
				.name {
				}
				.size {
					color: #515762;
				}
			}
			.file-delete {
				color: #eb3941;
				font-size: 28rpx;
				margin-right: 8rpx;
			}
			.file-download {
				color: #106aff;
				font-size: 28rpx;
			}
		}
		.file-image {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			gap: 10rpx;
			.image {
				width: 30rpx;
				height: 30rpx;
			}
		}
	}
	.item {
		width: 122rpx;
		height: 122rpx;
		position: relative;
		// border-radius: 20rpx;
		display: block;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		border: 2px solid #f5f5f5;
		box-sizing: border-box;
		.image {
			width: 100%;
			height: 100%;
			border-radius: 20rpx;
		}
		.delete {
			background: #eb3941;
			width: 35rpx;
			height: 35rpx;
			border-radius: 50%;
			position: absolute;
			top: -10rpx;
			right: -10rpx;
			z-index: 5;
			&::before,
			&::after {
				content: "";
				position: absolute;
				top: 0;
				bottom: 0;
				right: 0;
				left: 0;
				margin: auto;
				width: 60%;
				height: 2px;
				background: #fff;
			}
			&::before {
				transform: rotate(45deg);
			}
			&::after {
				transform: rotate(-45deg);
			}
		}
		.video {
			width: 100%;
			height: 100%;
		}
	}
	.box {
		display: flex;
		flex-direction: column;
	}
	.file-img {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 10rpx;
	}
	.upload {
		border: 0;
		&.disabled {
			opacity: 0.5;
		}
	}
}
</style>
